<template>
	<view>
		<cu-custom bgColor="bg-gradual-blue" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content" class="text-bold"> 发布骑行 </block>
		</cu-custom>
		<scroll-view>
			<view class="cu-form-group margin-top">
				<textarea maxlength="-1" :disabled="modalName!=null" @input="contentInput" style="height: 300upx;"
					placeholder="请输入要发布的内容"></textarea>
			</view>
			<view class="cu-bar bg-white margin-top">
				<view class="action">
					图片上传
				</view>
				<view class="action">
					{{imgList.length}}/{{maxImageSize}}
				</view>
			</view>
			<view class="cu-form-group ">
				<view class="grid col-3 grid-square flex-sub">
					<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="viewImage"
						:data-url="imgList[index].path">
						<image :src="imgList[index].path" mode="aspectFill"></image>
						<view class="cu-tag bg-red" @tap.stop="delImg" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
					</view>
					<view class="solids" @tap="chooseImage" v-if="imgList.length<maxImageSize">
						<text class='cuIcon-cameraadd'></text>
					</view>
				</view>
			</view>
			<view class="cu-form-group margin-top">
				<text class="cuIcon-phone"></text>
				<input placeholder="请输入手机号码" name="input" class="margin-left text-gray" v-model="phone"></input>
			</view>
			<view class="cu-form-group margin-top" @click="openMap(e)">
				<text class="cuIcon-locationfill text-red">
					<text class="text-gray text-df margin-left">{{position.address}}</text>
				</text>
				<text class="cuIcon-right"></text>
			</view>
			<view class="cu-form-group margin-top" @click="showTimeSelect = true">
				<view class="cuIcon-time text-grey">选择出发时间</view>
				<w-picker :visible.sync="showTimeSelect" mode="date" startYear="2017" endYear="2029" value="2020-04-07"
					:current="true" fields="minute" @confirm="onConfirm($event,'date')" :disabled-after="false"
					ref="date"></w-picker>
				<view>{{dateStr}}</view>
			</view>
			<view class="margin-top margin-left">
				<checkbox class="round green" :checked="agreement" disabled></checkbox>
				<text class="margin-left text-gray">发布信息前请先查看</text><text class="text-blue"
					@click="readDisclaimer">免责声明</text>
			</view>
			<button class=" bg-gradual-blue margin-top-xl cu-btn margin text-xxl"
				style="width: 90%; height: 80upx;font-family: 楷体;" @click="publisInfo" :disabled="!agreement">立即发布</button>
		</scroll-view>
	</view>
</template>

<script>
	var dateformat = require('@/static/js/dateformat.js')
	var constants = require('@/static/utils/constants.js')
	var http = require('@/static/utils/request.js')
	import QQMap from '@/static/js/QQMap.js'
	import wPicker from "@/components/w-picker/w-picker.vue"
	export default {
		data() {
			return {
				start: {},
				dest: {},
				polyline: {},
				startTime: '',
				endTime: '',
				dateStr: '2015-09-01',
				maxImageSize: 3,
				phone: '',
				imgList: [],
				images: [],
				mapApiUrl: 'https://apis.map.qq.com/ws/geocoder/v1/?',
				apiKey: '7SEBZ-2PKCJ-RQFFC-KAOO2-EVYB3-2UFNV',
				location: '',
				position: {
					address: '请规划骑行路线',
					latitude: '',
					longitude: ''
				},
				content: '',
				agreement: false,
				visiable: true,
				showTimeSelect: false
			};
		},
		components: {
			wPicker
		},
		created() {
			let that = this
			let nowTime = new Date()
			let now = dateformat.dateFormat('yyyy年MM月dd—HH点mm分', nowTime)
			// this.$data.startTime = now
			// this.$data.dateStr = now
			uni.$on("startAndDestSelectOK", data => {
				that.$data.start = data[0]
				that.$data.dest = data[1]
				that.polyline = data[2]
				that.$data.position.address = that.$data.start.title + "——" + that.$data.dest.title
			})
			uni.$on("agreement", data => {
				that.$data.agreement = data
			})
		},
		mounted() {

		},
		destroyed() {
			uni.$off("startAndDestSelectOK")
			uni.$off('agreement')
		},
		methods: {
			onConfirm(event, date) {
				let timeStr = event.result
				this.$data.startTime = timeStr
				let timeArr = timeStr.split(' ')
				let YMD = timeArr[0].split('-')
				let HM = timeArr[1].split(':')
				this.$data.dateStr = YMD[0] + '年' + YMD[1] + '月' + YMD[2] + '日' + '—' + HM[0] + '点' + HM[1] + '分'
			},
			/**
			 * 获取初始位置信息
			 */
			getInitialPosition() {
				let that = this
				uni.getLocation({
					type: 'gcj02',
					geocode: true, //设置该参数为true可直接获取经纬度及城市信息
					success: (res) => {
						let latitude = res.latitude
						let longitude = res.longitude
						that.$data.position.latitude = latitude
						that.$data.position.longitude = longitude
						QQMap.qqmapsdk.reverseGeocoder({
							location: {
								latitude: latitude,
								longitude: longitude
							},
							success: res => {
								that.$data.position.address = res.result.address
							},
							fail: err => {

							}
						})
					}
				})
			},
			publisInfo() {
				let _this = this
				uni.showModal({
					content: "确定要发布该信息吗",
					confirmColor: "red",
					confirmText: "确定",
					cancelText: "取消",
					success(succ) {
						if (succ.confirm) {
							let param = {}
							// debugger
							param.content = _this.$data.content
							// 构造images
							debugger
							_this.$data.imgList.forEach((item, index) => {
								let img = {
									id: index,
									url: item.url,
									type: 'image'
								}
								_this.$data.images.push(img)
							})
							param.pictures = _this.$data.images
							param.contractPhone = _this.$data.phone
							param.line = JSON.stringify(_this.$data.polyline)
							param.startingPoint = _this.$data.start.poi
							param.destination = _this.$data.dest.poi
							param.startTime = _this.$data.startTime
							let user = uni.getStorageSync('userInfo')
							param.publisher = user.id
							http.saveBikeInvitation(param).then(succ1 => {
								if (succ1.data.code === '2000') {
									uni.showToast({
										title: '信息发布成功',
										duration: 10000,
										image: '../../static/success.png',
										complete() {
											setTimeout(() => {
												uni.navigateBack()
											}, 3000)
										}
									})
								}
							})
						}
						if (succ.cancel) {}
					},
					fail(err) {}
				})
			},
			cancel() {
				this.$data.visiable = true
			},
			disclaimerCompleted(e) {
				this.$data.readCompleted = e
				this.$data.visiable = e
			},
			readDisclaimer() {
				uni.navigateTo({
					url: 'disclaimer/disclaimer'
				})
				this.$data.visiable = false
			},
			dateChange(e) {
				this.date = e.detail.value
			},
			/**
			 * 根据经纬度反向获取地址信息
			 * @param {Object} latitude
			 * @param {Object} longitude
			 */
			getAddress(latitude, longitude) {
				let that = this
				uni.request({
					method: 'GET',
					url: that.$data.mapApiUrl + 'location=' + latitude + ',' + longitude +
						'&' + 'key=' + that.$data.apiKey,
					success: res => {
						let address = res.data.result.address
						that.$data.position.address = address
					}
				})
			},
			/**
			 * 打开地图组件
			 */
			openMap(e) {
				uni.navigateTo({
					url: '../map/map'
				})
			},
			/**
			 * 选择 照片
			 */
			chooseImage() {
				let _this = this
				uni.chooseImage({
					count: 9, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: (res) => {
						console.log(res)
						let file = res.tempFiles[0]
						_this.uploadFile(file)
					}
				});
			},
			/**
			 * 上传文件
			 * @param {Object} file
			 */
			uploadFile(file) {
				let path = file.path
				let _this = this
				uni.uploadFile({
					// 需要上传的地址
					url: constants.uploadFileUrl,
					filePath: path,
					name: 'file',
					header: {
						'Content-Type': "multipart/form-data"
					},
					success: res => {
						let data = JSON.parse(res.data)
						if (data.code === '2000') {
							file.url = data.data
							_this.$data.imgList.push(file)
						}
					},
					fail: error => {}
				})
			},
			/**
			 * 查看照片
			 * @param {Object} e
			 */
			viewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			/**
			 * 删除照片
			 * @param {Object} e
			 */
			delImg(e) {
				uni.showModal({
					content: '确定要删除这张照片吗?',
					cancelText: '取消',
					confirmText: '确定',
					confirmColor: '#ED1C24',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			contentInput(e) {
				this.content = e.detail.value
			}
		}
	}
</script>

<style>
	.textarea-xl {
		height: 300upx;
	}
</style>
